import { createI18n } from 'vue-i18n'
import zh from './zh'
import en from './en'
import { App } from 'vue'
import { PageConfig } from '@/types/pageConfig'

const messages = {
  en,
  zh
}
/**
 * 自动注册菜单页面语言
 */
const autoRegisterPagesLang = () => {
  const enPages: Record<string, string> = {}
  const zhPages: Record<string, string> = {}
  const configs: Record<string, PageConfig> = import.meta.glob('@/modules/**/*.config.ts', {
    eager: true,
    import: 'default'
  })
  for (const key in configs) {
    if (configs[key].lang) {
      enPages[configs[key].lang!.en] = configs[key].lang!.en
      zhPages[configs[key].lang!.en] = configs[key].lang!.zh
    }
  }
  messages.en.pages = enPages
  messages.zh.pages = zhPages
}
autoRegisterPagesLang()

export type TLang = typeof zh

const language = (navigator.language || 'zh').toLocaleLowerCase()

const i18n = createI18n({
  locale: localStorage.getItem('lang') || language.split('-')[0] || 'zh',
  fallbackLocale: 'zh',
  allowComposition: true,
  legacy: false,
  messages
})

export function registerI18n(app: App) {
  app.use(i18n)
}

export default i18n
